package yesjava.news.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("*.do")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

//    http://.../list-news.do
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//       忽略登录的路径
        if(request.getRequestURI().indexOf("/login.do")!=-1){
            chain.doFilter(request,response);
            return;
        }

        boolean isLogin = (request.getSession().getAttribute("currentUserId")!=null);
        if(isLogin){
            chain.doFilter(request,response);
        }else {
            String lastURI = request.getRequestURI();
            request.getSession().setAttribute("lastURI",lastURI);
            request.setAttribute("msg","请登录后操作!");
            request.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(request,response);
        }

    }

    @Override
    public void destroy() {

    }
}
